<?php
/**
 * @author: wuwenhan <329576084@qq.com>
 * @copyright 综合管理系统
 * @link http://www.zhongkefu.com
 */

namespace zhongkefu\helpers;
use Yii;
use zhongkefu\zhongkefu;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

/**
 * Class Util
 * @package zhongkefu\helpers
 * @author: wuwenhan <329576084@qq.com>
 * @copyright zhongkefu
 * @link http://www.zhongkefu.com
 */
class Utils
{
    //传入月份，获取当前季度01~12
    public static function getQuarterByMonth($date){
        $Q = ceil($date/3);
        return $Q;
    }

    /**
     * 导出数据为excel表格
     * @param array $data 一个二维数组,结构如同从数据库查出来的数组
     * @param array $title excel的第一行标题,一个数组,如果为空则没有标题
     * @param string $filename 下载的文件名
     * @examlpe
     * $stu = M ('User');
     * $arr = $stu -> select();
     * exportexcel($arr,array('id','账户','密码','昵称'),'文件名!');
     */
    public static function exportExcel($data = array(), $title = array(), $filename = 'report')
    {
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:attachment;filename=" . $filename . ".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        //导出xls 开始
        if (!empty($title)) {
            foreach ($title as $k => $v) {
                $title[$k] = iconv("UTF-8", "GB2312", $v);
            }
            $title = implode("\t", $title);
            echo "$title\n";
        }
        if (!empty($data)) {
            foreach ($data as $key => $val) {
                foreach ($val as $ck => $cv) {
                    $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
                }
                $data[$key] = implode("\t", $data[$key]);

            }
            echo implode("\n", $data);
        }
    }
//zsn 20161230 清楚缓存文件
    public static function deldir($dir) { 
    //先删除目录下的文件： 
    $dh=opendir($dir); 
    while ($file=readdir($dh)) { 
        if($file!="." && $file!="..") { 
            $fullpath=$dir."/".$file; 
            if(!is_dir($fullpath)) { 
                unlink($fullpath); 
            } else { 
                Utils::deldir($fullpath); 
            } 
        } 
    } 
    closedir($dh); 
    //删除当前文件夹： 
    if(rmdir($dir)) { 
        return true; 
    } else { 
        return false; 
    } 
    } 
    public static function createcode($length = 8)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x', 'y','z', 'A', 'B', 'C', 'D',
            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L','M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y','Z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

        // 在 $chars 中随机取 $length 个数组元素键名
        $keys = array_rand($chars, $length);

        $password = '';
        for($i = 0; $i < $length; $i++)
        {
            // 将 $length 个数组元素连接成字符串
            $password .= $chars[$keys[$i]];
        }

        return $password;
    }
    //$c=1代表若未选周几则，默认上课时间为周一。,$da=16代表若未填写课时数，则默认课时数是16，填写则按照填写的走
    public static function munw($b,$e,$c=1,$da=16){
        $n=0;
        $t=array();
        $btime=strtotime($b[2]." ".Utils::getM($b[1])." ".$b[0]);
        $etime=strtotime($b[2]." ".Utils::getM($b[1])." ".$b[0])+365*24*3600;//截止时间=开始时间+一年的时间   因为回有调课，请假的情况，所以可能实际的截止时间要比截止时间晚的多（同样可能比用开始时间和课时计算出来的时间晚的多）

        for($i=$btime;$i<$etime;$i=$i+24*3600){
            if($n>=$da) {
                break;
            }
                if(date("N",$i)==$c){//date("N",$i)是周几：7、6、5、4、3、2、1、
                    $n++;
                    $t[]=date("Y-m-d",$i);
                }


        }

        return $t;
    }
    public static function munnum($b,$e,$c=1){
        $n=0;
        $t=array();
        $btime=strtotime($b[2]." ".Utils::getM($b[1])." ".$b[0]);
        $etime=strtotime($e[2]." ".Utils::getM($e[1])." ".$e[0].' 23:59:59');
        for($i=$btime;$i<$etime;$i=$i+86400){
            if(date("N",$i)==$c){
                $n++;
                $t[]=date("Y-m-d",$i);
            }
        }

        return $n;
    }
    public static function getM($m)
    {
        switch ($m) {
            case 1:
                return "January";
                break;
            case 2:
                return "February";
                break;
            case 3:
                return "March";
                break;
            case 4:
                return "April";
                break;
            case 5:
                return "May";
                break;
            case 6:
                return "June";
                break;
            case 7:
                return "July";
                break;
            case 8:
                return "August";
                break;
            case 9:
                return "September";
                break;
            case 10:
                return "October";
                break;
            case 11:
                return "November";
                break;
            case 12:
                return "December";
                break;
        }
    }

    /**
     * 合并行为用于在params中的配置
     * @param $className
     * @param $parentEvents
     * @return array
     */
    public static function eventMerge($className, $parentEvents)
    {
        $behavior = isset(zhongkefu::$app->params['events'][$className]) ? zhongkefu::$app->params['events'][$className] : [];
        return ArrayHelper::merge($parentEvents, $behavior);
    }
    /**
     * 合并行为用于在params中的配置
     * @param $className
     * @param $parentBehaviors
     * @return array
     */
    public static function behaviorMerge($className, $parentBehaviors)
    {
        $behavior = isset(zhongkefu::$app->params['behaviors'][$className]) ? zhongkefu::$app->params['behaviors'][$className] : [];
        return ArrayHelper::merge($parentBehaviors, $behavior);
    }

    #字符串匹配，sunday算法
    public static function sunday($patt, $text) {
        $patt_size = strlen($patt);
        $text_size = strlen($text);

        #初始化字符串位移映射关系
        #此处注意,映射关系表的建立一定是从左到右，因为patten可能存在相同的字符
        #对于重复字符的位移长度，我们只能让最后一个重复字符的位移长度覆盖前面的位移长度
        #例如pattern = "testing",注意到此处有2个t，那么建立出来的位移映射是 shift[] = Array ( [t] => 4 [e] => 6 [s] => 5 [i] => 3 [n] => 2 [g] => 1 )
        #而如果不是从左到右，是从右到左的建立映射，就会变成 shift[] = Array ( [t] => 7 [e] => 6 [s] => 5 [i] => 3 [n] => 2 [g] => 1 )，这样到时候匹配就无法得到正确结果
        for ($i = 0; $i < $patt_size; $i++) {
            $shift[$patt[$i]] = $patt_size - $i;
        }

        $i = 0;
        $pipei =[];
        $limit = $text_size - $patt_size; #需要开始匹配的最后一个字符坐标
        while ($i <= $limit) {
            $match_size = 0; #当前已匹配到的字符个数
            #从i开始匹配字符串
            while ($text[$i + $match_size] == $patt[$match_size]) {
                $match_size++;
                if ($match_size == $patt_size) {
                   array_push($pipei,$i) ;
                    break;
                }
            }

            $shift_index = $i + $patt_size; #在text中比pattern的多一位的字符坐标
            if ($shift_index < $text_size && isset($shift[$text[$shift_index]])) {
                $i += $shift[$text[$shift_index]];
            } else {
                #如果映射表中没有这个字符的位移量，直接向后移动patt_size个单位
                $i += $patt_size;
            }
        }
        return $pipei;
    }
    #上传文件
    public static function uploadfile($filetmpimg,$filename,$siteRoot){
        $tempPath = $filetmpimg;

        $filesName = uniqid() . '.' . pathinfo($filename, PATHINFO_EXTENSION);
        $uploadPath = $siteRoot . $filesName;

        move_uploaded_file($tempPath, $uploadPath);

        $answer = array('newname' => $filesName,'oldname'=>$filename);
        $json = json_encode($answer);
        return $json;
    }

	/**
	 * 下载远程图片
	 * @param string $url 图片的绝对url
	 * @param string $filepath 文件的完整路径（例如/www/images/test） ，此函数会自动根据图片url和http头信息确定图片的后缀名
	 * @param string $filename 要保存的文件名(不含扩展名)
	 * @return mixed 下载成功返回一个描述图片信息的数组，下载失败则返回false
	 */
	static public function downloadImage($url, $filepath, $filename) {
		//服务器返回的头信息
		$responseHeaders = array();
		//原始图片名
		$originalfilename = '';
		//图片的后缀名
		$ext = '';
		$ch = curl_init($url);
		//设置curl_exec返回的值包含Http头
		curl_setopt($ch, CURLOPT_HEADER, 1);
		//设置curl_exec返回的值包含Http内容
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		//设置抓取跳转（http 301，302）后的页面
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		//设置最多的HTTP重定向的数量
		curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
	
		//服务器返回的数据（包括http头信息和内容）
		$html = curl_exec($ch);
		//获取此次抓取的相关信息
		$httpinfo = curl_getinfo($ch);
		curl_close($ch);
		if ($html !== false) {
			//分离response的header和body，由于服务器可能使用了302跳转，所以此处需要将字符串分离为 2+跳转次数 个子串
			$httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
			//倒数第二段是服务器最后一次response的http头
			$header = $httpArr[count($httpArr) - 2];
			//倒数第一段是服务器最后一次response的内容
			$body = $httpArr[count($httpArr) - 1];
			$header.="\r\n";
	
			//获取最后一次response的header信息
			preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
			if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
				for ($i = 0; $i < count($matches[1]); $i++) {
					if (array_key_exists($i, $matches[2])) {
						$responseHeaders[$matches[1][$i]] = $matches[2][$i];
					}
				}
			}
			//获取图片后缀名
			if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp)$}i', $url, $matches)) {
				$originalfilename = $matches[0];
				$ext = $matches[1];
			} else {
				if (array_key_exists('Content-Type', $responseHeaders)) {
					if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
						$ext = $extmatches[1];
					}
				}
			}
			//保存文件
			if (!empty($ext)) {
				//如果目录不存在，则先要创建目录
				if(!is_dir($filepath)){
					mkdir($filepath, 0777, true);
				}
					
				$filepath .= '/'.$filename.".$ext";
				$local_file = fopen($filepath, 'w');
				if (false !== $local_file) {
					if (false !== fwrite($local_file, $body)) {
						fclose($local_file);
						$sizeinfo = getimagesize($filepath);
						return array('filepath' => realpath($filepath), 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
					}
				}
			}
		}
		return false;
	}
    //判断移动设备
    public static function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return true;

        //此条摘自TPM智能切换模板引擎，适合TPM开发
        if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
            return true;
        //如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA']))
            //找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
        //判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
            );
            //从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        //判断是否为ipad
        $ua = @$_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/ipad/i', $ua)) {

            return true;

        }
        //协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }
    //从数据库调取表单元素 $id为表单id cqn
    public static function bdelements($id)
    {
        //查询元素，然后循环所有表单元素
        $custom_elements = Yii::$app->db->createCommand('SELECT * FROM custom_elements where set_id='.$id)->queryAll();
        foreach ($custom_elements as $key => $value ) {
                if ($value["evalue"]) {
                    $custom_elements[$key]["value"] = unserialize($value["evalue"]);
                    unset($custom_elements[$key]["evalue"]);
                }
            }
        return json_encode($custom_elements);
    }
    //视图页面填写信息，post所有表单数据 cqn
    public static function eleadd($ac_id)
    {
        $array = array();
        foreach (Yii::$app->request->post() as $key => $value ) {
            if ($value == "") {
                $array[] = array($key => "未填写");
            }
        }
        $arr = array();
        foreach ($array as $k => $v ) {
            foreach ($v as $key => $value ) {
                $arr[$key] = $value;
            }
        }
        $b = Yii::$app->request->post();
        $request = array_merge($b, $arr);
        $sub_info = Utils::serializeSubInfo($request, $ac_id);
        return $sub_info;
    }
    //视图页面显示所有填写的表单信息 $id为表单信息id cqn
    public static function eleinfo($id)
    {
        $list = Yii::$app->db->createCommand("select sub_info from custom_info where info_id=".$id)->queryAll();
        foreach ($list as $key => $value) {
            $sub_info = unserialize($value['sub_info']);
            foreach ($sub_info as $k => $v ) {
                    if (($v["type"] == "picturecheckbox") || ($v["type"] == "fileupload")) {
                        $img = explode(",", $v["value"]);
                        foreach ($img as $kk => $vv ) {
                            if ($vv != "") {
                                $img[$kk] = "<img src=\"" . $vv . "\" width=\"50px\" height=\"50px\" />";
                            }
                            else {
                                $img[$kk] = ($v["type"] == "fileupload" ? "未上传" : "未选择");
                            }
                        }
                        $sub_info[$k]["value"] = implode(",", $img);
                    }
                    else if ($v["type"] == "pictureradio") {
                        if ($v["value"] != "") {
                            $sub_info[$k]["value"] = "<img src=\"" . $v["value"] . "\" width=\"50px\" height=\"50px\">";
                        }
                        else {
                            $sub_info[$k]["value"] = "未选择";
                        }
                    }
                }
        $list[$key]['sub_info'] = $sub_info;
        $list = $list[0]['sub_info'];
        }
        return $list;
    }

     //存表单信息 cqn
    public static function serializeSubInfo($post, $ac_id)
    {
        $bdinfo =  Yii::$app->db->createCommand("select cu_id from activity where ac_id=".$ac_id)->queryOne();
        $custom_elements =  Yii::$app->db->createCommand("select * from custom_elements where set_id=".$bdinfo['cu_id']." order by id asc ")->queryAll();
        $info = array();
        //$savepath = $this->savepath();
        //$info_path = parse_url($savepath);
        //$local_path = getcwd() . $info_path["path"];

        foreach ($custom_elements as $key => $value ) {
            if (($value["name"] == "id_section") || ($value["name"] == "id_picture")) {
                continue;
            }
            $info[$key]["name"] = ($value["title"] ? $value["title"] : $value["name"]);
            $info[$key]["type"] = substr($value["name"], 3);
            if (($value["name"] == "id_checkbox") || ($value["name"] == "id_picturecheckbox")) {
                $info[$key]["value"] = implode(",", $post[substr($value["name"], 3) . "_" . $value["eid"]]);
            }
            /*else if ($value["name"] == "id_fileupload") {
                foreach ($post[substr($value["name"], 3) . "_" . $value["eid"]] as $kk => $vv ) {
                    $picname = $value["eid"] . $kk . time() . ".png";
                    $filedata = base64_decode(substr($vv, 22));
                    $fp = fopen($local_path . $picname, "w");
                    fwrite($fp, $filedata);
                    fclose($fp);
                    $up_domainname = (C("up_domainname") ? str_replace("http://", "", C("up_domainname")) : "");
                    $upload_type = ((C("upload_type") != "") && ($up_domainname != "") ? C("upload_type") : "local");

                    if ($upload_type == "upyun") {
                        $back_json = $this->Upyun_upload($local_path . $picname);
                        $decode_json = json_decode($back_json, true);
                        if (($decode_json["code"] == 200) && ($decode_json["message"] == "ok")) {
                            unlink($local_path . $picname);
                            $info[$key]["value"] .= "http://" . $up_domainname . $decode_json["url"] . ",";
                        }
                        else {
                            $info[$key]["value"] .= $savepath . $picname . ",";
                        }
                    }
                    else {
                        $info[$key]["value"] .= $savepath . $picname . ",";
                    }
                }

                $info[$key]["value"] = trim($info[$key]["value"], ",");
            }*/
            else if ($value["name"] == "id_code") {
                $postcode = md5($post[substr($value["name"], 3) . "_" . $value["eid"]]);

                if ($postcode != $_SESSION["verifycustom"]) {
                    $this->error("验证码输入错误");
                }

                $info[$key]["value"] = $post[substr($value["name"], 3) . "_" . $value["eid"]];
            }
            else {
                $info[$key]["value"] = $post[substr($value["name"], 3) . "_" . $value["eid"]];
            }
        }

        return serialize($info);
    }

    /*private function savepath()
    {
        
        $savePath = "./uploads/" . $firstLetter . "/" . $this->token . "/";
        if (!file_exists($_SERVER["DOCUMENT_ROOT"] . "/uploads") || !is_dir($_SERVER["DOCUMENT_ROOT"] . "/uploads")) {
            mkdir($_SERVER["DOCUMENT_ROOT"] . "/uploads", 511);
        }

        $firstLetterDir = $_SERVER["DOCUMENT_ROOT"] . "/uploads/" . $firstLetter;
        if (!file_exists($firstLetterDir) || !is_dir($firstLetterDir)) {
            mkdir($firstLetterDir, 511);
        }

        if (!file_exists($firstLetterDir . "/" . $this->token) || !is_dir($firstLetterDir . "/" . $this->token)) {
            mkdir($firstLetterDir . "/" . $this->token, 511);
        }

        if (!file_exists($savePath) || !is_dir($savePath)) {
            mkdir($savePath, 511);
        }

        return $this->siteUrl . substr($savePath, 1);
    }*/
}